const express = require('express')
const { Op } = require('sequelize')
const router = express.Router()
const auth = require('../middleware/auth')
const logger = require('../utils/logger')
const notificationService = require('../services/notificationService')
const wechatTemplateService = require('../services/wechatTemplateService')
const { Message, NotificationLog } = require('../models')

/**
 * 获取用户消息列表
 * GET /api/messages
 */
router.get('/', auth, async (req, res) => {
  try {
    const { page = 1, limit = 20, type, isRead } = req.query
    const userId = req.user.id

    const whereClause = { userId }
    
    if (type) {
      whereClause.type = type
    }
    
    if (isRead !== undefined) {
      whereClause.isRead = parseInt(isRead)
    }

    const offset = (page - 1) * limit
    
    const { count, rows } = await Message.findAndCountAll({
      where: whereClause,
      order: [['createdAt', 'DESC']],
      limit: parseInt(limit),
      offset: parseInt(offset)
    })

    // 获取未读消息数量
    const unreadCount = await Message.count({
      where: {
        userId,
        isRead: 0
      }
    })

    res.json({
      success: true,
      code: 200,
      message: '获取消息列表成功',
      data: {
        messages: rows,
        pagination: {
          total: count,
          page: parseInt(page),
          limit: parseInt(limit),
          pages: Math.ceil(count / limit)
        },
        unreadCount
      }
    })
  } catch (error) {
    logger.error('获取消息列表失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取消息列表失败'
    })
  }
})

/**
 * 获取消息详情
 * GET /api/messages/:id
 */
router.get('/:id', auth, async (req, res) => {
  try {
    const { id } = req.params
    const userId = req.user.id

    const message = await Message.findOne({
      where: { id, userId }
    })

    if (!message) {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '消息不存在'
      })
    }

    res.json({
      success: true,
      code: 200,
      message: '获取消息详情成功',
      data: message
    })
  } catch (error) {
    logger.error('获取消息详情失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取消息详情失败'
    })
  }
})

/**
 * 标记消息为已读
 * PUT /api/messages/:id/read
 */
router.put('/:id/read', auth, async (req, res) => {
  try {
    const { id } = req.params
    const userId = req.user.id

    const message = await Message.findOne({
      where: { id, userId }
    })

    if (!message) {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '消息不存在'
      })
    }

    if (!message.isRead) {
      await message.update({
        isRead: 1,
        readTime: new Date()
      })
    }

    res.json({
      success: true,
      code: 200,
      message: '消息已标记为已读',
      data: message
    })
  } catch (error) {
    logger.error('标记消息已读失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '标记消息已读失败'
    })
  }
})

/**
 * 批量标记消息为已读
 * PUT /api/messages/batch/read
 */
router.put('/batch/read', auth, async (req, res) => {
  try {
    const { messageIds } = req.body
    const userId = req.user.id

    if (!messageIds || !Array.isArray(messageIds)) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '消息ID列表不能为空'
      })
    }

    const [updatedCount] = await Message.update(
      {
        isRead: 1,
        readTime: new Date()
      },
      {
        where: {
          id: { [Op.in]: messageIds },
          userId,
          isRead: 0
        }
      }
    )

    res.json({
      success: true,
      code: 200,
      message: '批量标记已读成功',
      data: { updatedCount }
    })
  } catch (error) {
    logger.error('批量标记已读失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '批量标记已读失败'
    })
  }
})

/**
 * 标记所有消息为已读
 * PUT /api/messages/all/read
 */
router.put('/all/read', auth, async (req, res) => {
  try {
    const userId = req.user.id

    const [updatedCount] = await Message.update(
      {
        isRead: 1,
        readTime: new Date()
      },
      {
        where: {
          userId,
          isRead: 0
        }
      }
    )

    res.json({
      success: true,
      code: 200,
      message: '全部消息已标记为已读',
      data: { updatedCount }
    })
  } catch (error) {
    logger.error('标记全部已读失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '标记全部已读失败'
    })
  }
})

/**
 * 删除消息
 * DELETE /api/messages/:id
 */
router.delete('/:id', auth, async (req, res) => {
  try {
    const { id } = req.params
    const userId = req.user.id

    const deletedCount = await Message.destroy({
      where: { id, userId }
    })

    if (deletedCount === 0) {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '消息不存在'
      })
    }

    res.json({
      success: true,
      code: 200,
      message: '消息删除成功'
    })
  } catch (error) {
    logger.error('删除消息失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '删除消息失败'
    })
  }
})

/**
 * 发送测试通知
 * POST /api/messages/test
 */
router.post('/test', auth, async (req, res) => {
  try {
    const { type, data } = req.body
    const userId = req.user.id

    if (!type) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '通知类型不能为空'
      })
    }

    const result = await notificationService.sendNotification(userId, type, data || {})

    res.json({
      success: true,
      code: 200,
      message: '测试通知发送成功',
      data: result
    })
  } catch (error) {
    logger.error('发送测试通知失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '发送测试通知失败',
      error: error.message
    })
  }
})

/**
 * 获取通知发送统计
 * GET /api/messages/statistics
 */
router.get('/statistics/overview', auth, async (req, res) => {
  try {
    const { startDate, endDate } = req.query
    const userId = req.user.id

    // 获取微信模板消息统计
    const wechatStats = await wechatTemplateService.getSendStatistics({
      startDate,
      endDate,
      userId
    })

    // 获取站内消息统计
    const whereClause = { userId }
    if (startDate && endDate) {
      whereClause.createdAt = {
        [Op.between]: [startDate, endDate]
      }
    }

    const [totalMessages, readMessages] = await Promise.all([
      Message.count({ where: whereClause }),
      Message.count({ where: { ...whereClause, isRead: 1 } })
    ])

    const messageStats = {
      total: totalMessages,
      read: readMessages,
      unread: totalMessages - readMessages,
      readRate: totalMessages > 0 ? ((readMessages / totalMessages) * 100).toFixed(2) : 0
    }

    res.json({
      success: true,
      code: 200,
      message: '获取通知统计成功',
      data: {
        wechat: wechatStats,
        inApp: messageStats
      }
    })
  } catch (error) {
    logger.error('获取通知统计失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取通知统计失败'
    })
  }
})

/**
 * 重试失败的通知
 * POST /api/messages/retry/:logId
 */
router.post('/retry/:logId', auth, async (req, res) => {
  try {
    const { logId } = req.params
    const userId = req.user.id

    // 验证日志是否属于当前用户
    const log = await NotificationLog.findOne({
      where: { id: logId, userId }
    })

    if (!log) {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '通知日志不存在'
      })
    }

    const result = await wechatTemplateService.retryFailedNotification(logId)

    res.json({
      success: true,
      code: 200,
      message: '重试通知成功',
      data: result
    })
  } catch (error) {
    logger.error('重试通知失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '重试通知失败',
      error: error.message
    })
  }
})

module.exports = router